﻿#region Copyright © 2008-2009, DevExpressContrib (MIT License)
// This software is licensed under The MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion

namespace DevExpressContrib.Core.Ux
{
    using System;
    using System.Windows.Forms;
    using DevExpressContrib.Core.Interface;

    /// <summary>
    /// Class to process unhandled exceptions. Uses a custom dialog to display
    /// user friendly exception handling.
    /// </summary>
    public class DxExceptionHandler : ExceptionHandlerBase, IExecptionHandler
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DxExceptionHandler"/> class.
        /// </summary>
        public DxExceptionHandler(IServicesHelper servicesHelper) : base(servicesHelper) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:DevExpressContrib.Core.ExceptionHandlerBase">ExceptionHandlerBase</see> class. 
        /// </summary>
        public DxExceptionHandler(IServicesHelper servicesHelper, bool useExceptionHandlerDuringDebugging)
            : base(servicesHelper, useExceptionHandlerDuringDebugging) { }

        /// <summary>
        /// Gets or sets user defined additional information interface. This can be used to inject
        /// a user control into the exception handler and pass that information back via email.
        /// </summary>
        /// <value>The user defined additional information interface.</value>
        public override IExceptionHandlerUserDefined UserDefined { get; set; }

        /// <summary>
        /// Shows the specified exception.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="args">The exception arguments.</param>
        /// <returns>The forms <see cref="DialogResult"/></returns>
        public override DialogResult Show(Exception exception, ExceptionHandlerArgs args)
        {
            GuardAgainst.ArgumentIsNull(args, "args");
            DialogResult result;
            using (DxThreadExceptionDialog dialog = new DxThreadExceptionDialog(GetServicesHelper()))
            {
                InitializeExceptionDialog(exception, args, dialog);
                LogException(exception, dialog);
                result = dialog.ShowDialog();
                if (dialog.SendEmail)
                {
                    string userDefined = string.Empty;
                    if (UserDefined != null)
                        userDefined = UserDefined.Data;
                    SendEmail(exception, dialog.FromEmail, dialog.IncludeScreenshotInEmail, dialog.Screenshot);
                    if (!String.IsNullOrEmpty(dialog.FromEmail) && EmailHelper.IsEmailAddressWellFormed(dialog.FromEmail))
                        WriteFromEmailAddress(dialog.FromEmail);
                }

                if (result == DialogResult.Abort || args.IsFatal)
                {
                    GetServicesHelper().LogFatal("Exiting Application.");
                    Environment.Exit(args.ExitCode);
                }
            }
            return result;
        }

        private void InitializeExceptionDialog(Exception exception, ExceptionHandlerArgs args, DxThreadExceptionDialog dialog)
        {
            SetDefaultExceptionHandlerValues(args);

            dialog.Text = args.Caption;
            dialog.WhatHappenedCaption = args.WhatHappenedCaption;
            dialog.HowAffectedCaption = args.HowAffectedCaption;
            dialog.WhatToDoCaption = args.WhatToDoCaption;
            dialog.EmailInformationCaption = args.EmailInformationCaption;

            dialog.DetailText = ExceptionDetails(exception);
            dialog.WhatHappenedText = args.WhatHappenedText;
            dialog.HowAffectedText = args.HowAffectedText;
            dialog.WhatToDoText = args.WhatToDoText;
            dialog.EmailInformationText = args.EmailInformationText;

            dialog.IsFatal = args.IsFatal;
            dialog.Screenshot = GetScreenshot();
            dialog.FromEmail = ReadFromEmailAddress();
            dialog.ShowEmailControls = CanSendEmail();

            if (UserDefined != null)
                dialog.UserDefined = UserDefined;
        }

        private void LogException(Exception exception, DxThreadExceptionDialog dialog)
        {
            const string message = "Unhandled Exception";
            if (dialog.Screenshot != null)
                GetServicesHelper().LogException(message, exception, dialog.DetailText, dialog.Screenshot);
            else
                GetServicesHelper().LogException(message, exception, dialog.DetailText);
        }
    }
}
